package com.wan37.logic.listener.handler;

import com.wan37.logic.domain.entity.UserItemDO;
import com.wan37.logic.domain.vo.ItemVO;
import com.wan37.logic.global.reference.SpringContextHolder;
import com.wan37.logic.listener.annotation.EventHandler;
import com.wan37.logic.listener.annotation.Listener;
import com.wan37.logic.listener.event.EventType;
import com.wan37.logic.listener.event.user.UserLoginEvent;
import com.wan37.logic.service.UserItemService;
import com.wan37.logic.service.cache.ItemServiceCache;
import com.wan37.logic.service.cache.RoleServiceCache;
import com.wan37.logic.service.cache.UserServiceCache;
import com.wan37.protobuf.constant.BackpackLabel;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author : luoyong
 * @date : 2020-06-29 11:51
 **/
@Listener
public class ItemListenerHandler {
    private UserItemService userItemService;
    private ItemServiceCache itemServiceCache;
    private RoleServiceCache roleServiceCache;
    private UserServiceCache userServiceCache;

    public ItemListenerHandler() {
        this.userItemService = SpringContextHolder.getBean("userItemService");
        this.itemServiceCache = SpringContextHolder.getBean("itemServiceCache");
        this.roleServiceCache = SpringContextHolder.getBean("roleServiceCache");
        this.userServiceCache = SpringContextHolder.getBean("userServiceCache");
    }

    @EventHandler(value = EventType.LOGIN)
    public void login(UserLoginEvent userLoginEvent) {

        List<UserItemDO> userItemDOList = userItemService.getUserItemDOsByUserId(userLoginEvent.getUserId());
        Map<String, ItemVO> itemVOMap = new HashMap<>();
        ItemVO newItem = null;
        for (UserItemDO userItemDO : userItemDOList) {
            newItem = new ItemVO(userItemDO);
            ItemVO itemVO = itemServiceCache.getItemServiceMap().get(userItemDO.getItemId()).getItemVO();
            newItem.setLabel(BackpackLabel.ITEM);
            newItem.setMaxRepetition(itemVO.getMaxRepetition());
            newItem.setNumberMap(itemVO.getNumberMap());
            newItem.setName(itemVO.getName());
            newItem.setEnglishName(itemVO.getEnglishName());
            itemVOMap.put(newItem.getBackpackId(), newItem);
        }
        userServiceCache.getUserServiceMap().get(userLoginEvent.getUserId()).setItemVOMap(itemVOMap);
    }
}
